import sys
from PyQt5.QtWidgets import QInputDialog ,QGraphicsSimpleTextItem,QGraphicsPathItem,QApplication, QMainWindow, QGraphicsView, QGraphicsScene, QGraphicsRectItem, QGraphicsEllipseItem, QGraphicsLineItem, QGraphicsPolygonItem, QGraphicsTextItem, QAction, QVBoxLayout, QHBoxLayout, QWidget, QPushButton
from PyQt5.QtCore import Qt, QRectF, QLineF, QPointF
from PyQt5.QtGui import QPen, QColor, QPolygonF,QPainterPath,QFont

class GraphicsView(QGraphicsView):
    def __init__(self, h_ruler, v_ruler, scene, parent=None):
        super().__init__(scene, parent)
        self.h_ruler = h_ruler
        self.v_ruler = v_ruler
        self.shape = 'jiantou'  # Default shape
        self.color = Qt.black
        self.drawing = False

        # Center the scene's origin to match the rulers' origin
        self.setSceneRect(QRectF(-280, -280, 560 + 210, 560 + 297))
        self.setAlignment(Qt.AlignLeft | Qt.AlignTop)

        # Define the A4 area
        self.a4_rect = QRectF(0, 0, 210, 297)  # Size in points

        # Temporary item while drawing
        self.temp_item = None

    def wheelEvent(self, event):
        zoom_in_factor = 1.25
        zoom_out_factor = 1 / zoom_in_factor

        old_pos = self.mapToScene(event.pos())

        if event.angleDelta().y() > 0:
            zoom_factor = zoom_in_factor
        else:
            zoom_factor = zoom_out_factor

        self.scale(zoom_factor, zoom_factor)

        new_pos = self.mapToScene(event.pos())
        delta = new_pos - old_pos
        self.translate(delta.x(), delta.y())
        self.h_ruler.setScale(self.transform().m11())
        self.v_ruler.setScale(self.transform().m22())

        self.h_ruler.update()
        self.v_ruler.update()

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.start_pos = self.mapToScene(event.pos())
            self.drawing = True

    def mouseMoveEvent(self, event):
        if self.drawing:
            if self.temp_item:
                self.scene().removeItem(self.temp_item)

            self.updateShape(self.mapToScene(event.pos()), temporary=True)

    def mouseReleaseEvent(self, event):
        if self.drawing:
            self.drawing = False
            if self.temp_item:
                self.scene().removeItem(self.temp_item)
            self.updateShape(self.mapToScene(event.pos()), temporary=False)

    def updateShape(self, end_pos, temporary=False):
        try:
            start_pos = self.start_pos
            rect = QRectF(start_pos, end_pos).normalized()


            if not self.a4_rect.contains(rect):
                return  # Do not draw if the shape is not within the A4 area

            if self.shape == 'Rectangle':
                item = QGraphicsRectItem(rect)
            elif self.shape == 'Ellipse':
                item = QGraphicsEllipseItem(rect)
            elif self.shape == 'Line':
                line = QLineF(start_pos, end_pos)
                if not self.a4_rect.contains(line.p1()) or not self.a4_rect.contains(line.p2()):
                    return
                item = QGraphicsLineItem(line)
            elif self.shape == 'Polygon':
                # For polygons, check if any point is outside the A4 area
                points = [start_pos, end_pos]
                polygon = QPolygonF(points)
                if not self.a4_rect.contains(polygon.boundingRect()):
                    return
                item = QGraphicsPolygonItem(polygon)
            elif self.shape == 'jiantou':
                return
            elif self.shape == "quxian":
                # 创建 QPainterPath 对象
                path = QPainterPath()

                # 起点
                path.moveTo(QPointF(0, 0))

                # 绘制 S 曲线的路径
                path.cubicTo(QPointF(50, 100), QPointF(150, -100), QPointF(200, 0))

                # 创建 QGraphicsPathItem，并设置路径
                item = QGraphicsPathItem(path)
            elif self.shape == "ziti":
                # Prompt user for text input
                text, ok = QInputDialog.getText(self, "Input Text", "Enter text:")
                if ok and text:
                    # Add QGraphicsSimpleTextItem with the input text
                    item = QGraphicsSimpleTextItem(text)
                    item.setFont(QFont("Arial", 14))  # Set the font size and style
                    item.setPos(50, 50)  # Set position in the scene
                    #self.scene.addItem(item)
                #item = QGraphicsSimpleTextItem("Simple Text")
                #item.setPos(start_pos)  # Set position in the scene
            item.setPen(QPen(self.color))

            if temporary:
                # Only show as a temporary shape while drawing
                self.temp_item = item
                self.scene().addItem(self.temp_item)
            else:
                # Finalize the shape and add to the scene
                self.scene().addItem(item)
        except Exception as e:
            print(e)

    def setShape(self, shape):
        self.shape = shape

    def setColor(self, color):
        self.color = color